package com.leyou.item.service.impl;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 处理请求和响应的方法
 *
 * @version V1.0
 * @package com.leyou.item.service.impl
 * @description:
 * @author: pc
 * @date: 2019/6/23 17:29
 */
@Service("categoryService")
public class CategoryServiceImpl implements ICategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<CategoryDTO> queryCategoryByParentId(Long pid) {
        Category category = new Category();
        category.setParentId(pid);
        List<Category> list = categoryMapper.select(category);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }

        //原始方法
        /*List<CategoryDTO> result = new ArrayList<>();
        for (Category c : list) {
            CategoryDTO dto = new CategoryDTO();
            dto.setId(c.getId());
            dto.setIsParent(c.getIsParent());
            dto.setName(c.getName());
            dto.setSort(c.getSort());
            result.add(dto);
        }*/

        //封装方式
        return BeanHelper.copyWithCollection(list,CategoryDTO.class);
    }

    @Override
    public List<CategoryDTO> queryCategoryByIds(List<Long> ids){
        List<Category> list = categoryMapper.selectByIdList(ids);
        if (CollectionUtils.isEmpty(list)) {
            // 没找到，返回404
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, CategoryDTO.class);
    }
}
